package com.nebula.maven.springbootmebula.nebula;


import com.nebula.maven.springbootmebula.beetl.BeetlTextRender;
import com.nebula.maven.springbootmebula.beetl.XmlTemplateResourceLoader;
import com.vesoft.nebula.client.graph.SessionPool;
import com.vesoft.nebula.client.graph.SessionPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GroupTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Configuration
public class NebulaAutoConfig {

    @Bean
    @ConditionalOnProperty(name = "nebula.enabled", havingValue = "true")
    SessionPool sessionPool(NebulaGraphConfig properties){

        List<HostAddress> addressList = Arrays.stream(properties.getAddresses().split(","))
                .map(addr -> {
                    String[] parts = addr.split(":");
                    return new HostAddress(parts[0], Integer.parseInt(parts[1]));
                })
                .toList();
        SessionPoolConfig sessionPoolConfig = new SessionPoolConfig(addressList,
                properties.getSpace(), properties.getUsername(), properties.getPassword());
        sessionPoolConfig.setRetryTimes(3);
        sessionPoolConfig.setIntervalTime(1000);
        sessionPoolConfig.setMaxSessionSize(properties.getMaxSession());
        sessionPoolConfig.setMinSessionSize(1);
       return new SessionPool(sessionPoolConfig);
    }

    @Bean
    @ConditionalOnBean({SessionPool.class})
    public BeetlTextRender beetlTextRender() {
        XmlTemplateResourceLoader resourceLoader = new XmlTemplateResourceLoader("nebula/graph-query.xml");
        org.beetl.core.Configuration cfg = null;

        try {
            cfg = org.beetl.core.Configuration.defaultConfiguration();
            cfg.setStatementStart("@");
            cfg.setStatementEnd((String)null);
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            return new BeetlTextRender(gt);
        } catch (IOException var4) {
            IOException e = var4;
            throw new RuntimeException(e);
        }
    }


    @Bean
    @ConditionalOnBean(SessionPool.class)
    public NebulaTemplate nebulaTemplate(SessionPool sessionPool ) {
        return new NebulaTemplate(sessionPool);
    }

}
